from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
import hashlib
from Buyer.models import *
from data_sources import *


def LoginValid(func):
    def inner(request, *args, **kwargs):
        cookie_id = request.COOKIES.get('id')
        cookie_phone = request.COOKIES.get('phone')
        session_id = request.session.get('id')
        if cookie_id and cookie_phone and session_id:
            return func(request, *args, **kwargs)
        else:
            return HttpResponseRedirect('/Buyer/login/')
    return inner


def setPassword(password):
    md5 = hashlib.md5()
    md5.update(password.encode())
    result = md5.hexdigest()
    return result


def register(request):
    error_message = ''
    if request.method == 'POST':
        phone = request.POST.get('phone')
        if phone:
            if phone.isdigit() and len(phone) == 11 and phone.startswith('1'):
                user = BuyerUser.objects.filter(telephone=phone).first()
                if not user:
                    password = request.POST.get('password')
                    password_to = request.POST.get('password_to')
                    if password == password_to:
                        new_user = BuyerUser()
                        new_user.telephone = phone
                        new_user.password = setPassword(password=password)
                        username = request.POST.get('username')
                        if not username:
                            new_user.username = '宝妈'
                        else:
                            new_user.username = username
                        new_user.save()
                        return HttpResponseRedirect('/Buyer/login/')
                    else:
                        error_message = '两次密码不一致'
                else:
                    error_message = '手机已经被注册，请直接登录'
            else:
                error_message = '手机号格式错误'
        else:
            error_message = '手机号不可以为空'
    return render(request, 'buyer/register.html', locals())


def login(request):
    error_message = ''
    if request.method == 'POST':
        phone = request.POST.get('phone')
        if phone:
            user = BuyerUser.objects.filter(telephone=phone).first()
            if user:
                password = request.POST.get('password')
                db_password = user.password
                if db_password == setPassword(password):
                    response = HttpResponseRedirect('/Buyer/index/')
                    response.set_cookie('phone', user.telephone)
                    response.set_cookie('id', user.id)
                    request.session['id'] = user.id
                    return response
                else:
                    error_message = '密码错误，请查证'
            else:
                error_message = '用户名不存在'
        else:
            error_message = '邮箱不能为空'
    return render(request, 'buyer/login.html', locals())


def base(request):
    return render(request, 'buyer/base.html', locals())


@LoginValid
def index(request):
    return render(request, 'buyer/index.html', locals())


@LoginValid
def personal_info(request):
    return render(request, 'buyer/personal_info.html', locals())


@LoginValid
def all_goods(request, type):
    if type == '0':
        good_list = Goods.objects.all()
        goods_len = len(good_list)
    else:
        good_list = Goods.objects.filter(goods_type=type)
        goods_len = len(good_list)
    return render(request, 'buyer/all_goods.html', locals())


@LoginValid
def tuan_gou(request):
    return render(request, 'buyer/tuan_gou.html', locals())


@LoginValid
def zi_xun(request):
    return render(request, 'buyer/zi_xun.html', locals())


@LoginValid
def jian_jie(request):
    return render(request, 'buyer/jianjie.html', locals())


@LoginValid
def shopping_car(request):
    return render(request, 'buyer/shopping_cart.html', locals())


@LoginValid
def detail(request,id):
    # id = request.GET.get('id')
    goods = Goods.objects.get(id=int(id))
    return render(request, 'buyer/detail.html', locals())


def test(request):
    good = Goods.objects.get(id=1)
    return render(request, 'buyer/test.html', locals())


def create_data(request):
    import requests
    from lxml import etree
    import urllib
    from bs4 import BeautifulSoup

    import random
    import time


    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36'
    }
    types = ['进口奶粉', '宝宝辅食', '营养品', '纸尿裤', '婴儿湿巾',
             '婴儿车', '婴儿床', '儿童安全座椅', '儿童玩具', '早教书籍', '孕产育儿书',
             '童装', '童鞋', '宝宝配饰', '孕妇装', '孕妇护肤', '孕妇用品']
    location = ['四川', '深圳', '杭州', '北京', '江苏', '云南', '山东', '广东', '江西', '河南', '河北', '湖南', '湖北', '山西', '陕西']
    store = ['好佳佳母婴店', '亲亲宝贝', '宝宝最爱', '妈妈咪呀', '嗨乐购']
    for i in range(1, len(types) + 1, 1):
        for j in range(1, 25):
            url = 'http://s.leyou.com.cn/search?key={}&page={}'.format(types[i - 1], j)
            content = requests.get(url, headers=headers).content.decode('utf-8')
            tree = etree.HTML(content)
            div_list = tree.xpath(r'//div[@class="wrapperList"]/div[@class="products"]')
            print(url)
            for div in div_list:
                goods = Goods()
                src = div.xpath(r'./span[@class="pic"]/a/img/@src')[0]
                href = div.xpath(r'./span[@class="pic"]/a/@href')[0]
                price = div.xpath(r'./span[@class="disPrice"]/text()')[0].replace('￥', '').replace(',', '')
                title = div.xpath(r'./span[@class="intro"]/a/@title')[0]
                # print('11111111111')
                goods.goods_picture = src
                goods.goods_title = title
                goods.goods_current_price = price
                # print(type(price))
                goods.goods_RP = str(float(price) + float(random.randint(20, 200)))
                goods.goods_count = str(random.randint(10, 500))
                goods.goods_safe_date = str(random.randint(6, 36))

                goods.goods_location = random.choice(location)
                goods.goods_status = 1
                goods.goods_people_buy = random.randint(0, 500)
                goods.goods_type = GoodsType.objects.get(id=i)
                goods.goods_store = BuyerUser.objects.get(id=1)
                goods.goods_detai_href = href
                # print(src, '\n', href, '\n', price, '\n', title, '\n')
                goods.save()
    return HttpResponse('读取数据成功')


def goods_type(request):
    id=request.GET.get('id')
    print(1111111)
    goods_list=Goods.objects.filter(goods_type_id=int(id))
    print(goods_list)

    # g_type=GoodsType.objects.all()
    # for ty in g_type:
    #     goods_list=g_type.goods_set.order_by('')



    return render(request, 'buyer/goods_type.html', locals())


# Create your views here.
